import math
import queue
import time

import requests as r


def bangumi_follow_api(uid, follow_status, page, page_size):
    time.sleep(5)
    print(f'request{page}')
    resp = r.get(
        f'https://api.bilibili.com/x/space/bangumi/follow/list?type=1&follow_status={follow_status}&pn={page}&ps={page_size}&vmid={uid}')

    return resp.json()


class BiliAPI(object):
    PAGE_SIZE = 15

    def __init__(self, uid, follow_status):
        self.uid = uid
        self.follow_status = follow_status

        self.current_page = 0
        self.queue = queue.SimpleQueue()

    def __iter__(self):
        return self

    def __next__(self):
        if self.current_page == 0:
            data = bangumi_follow_api(self.uid, self.follow_status, 1, self.PAGE_SIZE)
            self.plan_page = math.ceil(data['data']['total'] / self.PAGE_SIZE)
            print(f"Total record: {data['data']['total']}")
            self.current_page = self.current_page + 1

        if self.queue.empty():
            if self.current_page > self.plan_page:
                raise StopIteration
            data = bangumi_follow_api(self.uid, self.follow_status, self.current_page, self.PAGE_SIZE)
            self.current_page = self.current_page + 1
            for item in data['data']['list']:
                self.queue.put(item)

        return self.queue.get()
